<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="icon" href="${pageContext.request.contextPath}/lib/static/login/images/favicon.ico">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/lib/layui/css/layui.css" media="all">
    <script src="${pageContext.request.contextPath}/lib/static/common/js/jquery.min.js"></script>
    <script src="${pageContext.request.contextPath}/lib/layui/layui.js" charset="utf-8"></script>
</head>
<body>
<div class="layui-fluid">
    <div class="layui-row">
        <fieldset class="layui-elem-field layui-field-title">
            <legend>配置管理</legend>
        </fieldset>
    </div>
    <hr class="layui-bg-red">

    <!--按钮及查询框组-->
    <div class="layui-row">
        <div class="layui-col-md-offset1">
            <form class="layui-form">
            <div class="layui-inline">
                <input class="layui-input" id="criteria" name="criteria"  autocomplete="off" placeholder="名称/值/描述">
            </div>
            <button class="layui-btn layuiadmin-btn-admin" lay-submit="" lay-filter="search">
                <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
            </button>
            </form>
        </div>
    </div>

    <table class="layui-hide" id="test" lay-filter="test"></table>

    <script type="text/html" id="toolbar">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm" lay-event="refresh"
                    onclick="window.location.href='${pageContext.request.contextPath}/sys/config/config_ui';">刷新
            </button>
            <button class="layui-btn layui-btn-sm" lay-event="delAll">删除</button>
            <button class="layui-btn layui-btn-sm" lay-event="add">新增</button>
        </div>
    </script>

    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>

    <script>
        var baseUrl = '${pageContext.request.contextPath}/sys/config/';

        /*发送ajax请求访问后台*/
        function sendAjaxPostReq($, param, tableUserIns, method) {
            $.post(
                baseUrl + method,
                param,
                function (result) {
                    if (result.code == 0) {
                        layer.msg(result.msg, {icon: 1});
                        /*刷新表格数据*/
                        tableUserIns.reload({
                            url: baseUrl + "get"
                        });
                    } else {
                        layer.msg(result.msg, {icon: 5});
                    }
                },
                "json"
            );
        }

        layui.use('table', function () {
            var table = layui.table;
            var form = layui.form;
            var configTable=  table.render({
                elem: '#test'
                ,toolbar: '#toolbar'
                ,url:baseUrl +'get'
                /*修改默认向后台传递的页码、大小参数名 @sunb*/
                ,request: {
                    pageName: 'pageNo' //页码的参数名称，默认：page
                    ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
                }
                ,height: 'full-150'
                ,cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                ,cols: [[{type: 'checkbox', fixed: 'left'}
                        ,{field:'name', title: '配置名称',sort: true, align: 'center'}
                        ,{field:'value', title: '配置值',sort: true, align: 'center'}
                        ,{field:'desc', title: '配置描述',sort: true, align: 'center'}
                        ,{field:'addTime', title: '添加时间',sort: true, align: 'center',templet:'<div>{{layui.laytpl.toDateString(d.addTime)}}</div>'}
                        ,{field:'updateTime', title: '修改时间',sort: true, align: 'center',templet:'<div>{{layui.laytpl.toDateString(d.updateTime)}}</div>'}
                        ,{fixed:'right', title: '操作',toolbar: '#barDemo', align: 'center', width:150}
                ]]
                ,page: {
                    layout: ['limit', 'count', 'prev', 'page', 'next', 'skip']
                    ,groups: 3
                }
            });

            //时间戳处理
            layui.laytpl.toDateString=function(d,format){
                if(!d){
                    return "";
                }
                var date = new Date(d)
                ,ymd=[
                    this.digit(date.getFullYear(),4)
                    ,this.digit(date.getMonth()+1)
                    ,this.digit(date.getDate())
                    ]
                 ,hms=[
                    this.digit(date.getHours())
                    ,this.digit(date.getMinutes())
                    ,this.digit(date.getSeconds())
                ];
                format=format||'yyyy-MM-dd HH:mm:ss';
                return format.replace(/yyyy/g,ymd[0])
                    .replace(/MM/g,ymd[1])
                    .replace(/dd/g,ymd[2])
                    .replace(/HH/g,hms[0])
                    .replace(/mm/g,hms[1])
                    .replace(/ss/g,hms[2])
            };
            //数字前置补零
            layui.laytpl.digit = function(num,length,end){
                var str='';
                num = String(num);
                length=length ||2;
                for(var i=num.length;i<length;i++){
                    str +='0';
                }
                return num<Math.pow(10,length) ? str+(num|0):num;
            };

            //头工具栏事件
            table.on('toolbar(test)', function (obj) {
                var checkStatus = table.checkStatus(obj.config.id);
                switch (obj.event) {
                    case 'delAll':
                        var url1 = baseUrl+'deleteByIds';
                        var data  = checkStatus.data;//返回一个数组
                        layer.confirm("您选中了" +data.length + "条数据，确认删除？", function (index) {
                            var ids=[];
                            for(var i in data){
                                var id=data[i].id;
                                console.log("id:"+id);
                                ids[i]=id;
                            }
                            $.post(url1,{"ids":ids.toString()},function(result){
                                if(result.code==0){
                                    layer.close(index);
                                    layer.msg(result.msg, {icon: 1});
                                    configTable.reload({
                                        url: baseUrl+'get'
                                    });

                                }else {
                                    layer.close(index);
                                    layer.msg(result.msg, {icon: 5});
                                }
                            });
                        });

                        break;
                    case 'add':
                        openConfigLayer("配置添加","config_edit")
                        break;
                }
            });

            /*弹框公用方法*/
            function openConfigLayer(title,url,config) {
                layer.open({
                    content: [baseUrl + url],
                    type: 2,
                    title: '<h2>'+ title +'</h2>',
                    maxmin: true,
                    shadeClose: true, //点击遮罩关闭层
                    offset: '150px',
                    area: ['600px', '330px'],
                    closeBtn: 2,
                    success: function (layero, index) {
                        var body = layer.getChildFrame('body', index);
                        body.find("input[name='name']").val(config.name);
                        body.find("input[name='value']").val(config.value);
                        body.find("input[name='desc']").val(config.desc);
                        layer.iframeAuto(index);
                        return false;
                    }
                });
            }

            form.verify({
                criteria: function (value, item) { //value：表单的值、item：表单的DOM对象
                    if (value.length == 0) {
                        return '请输入查询内容';
                    }
                },
            });
            /* 查询 */
            form.on('submit(search)', function (data) {
                configTable.reload({
                    url: baseUrl+'get'
                    , method: "post" /*解决参数传递中文乱码*/
                    , where: data.field
                });
                return false;
            });

            //监听行工具事件
            table.on('tool(test)', function (obj) {
                var data = obj.data;
                var params = {"id":data.id};
                var url = '${pageContext.request.contextPath}/sys/config/deleteById';
                if (obj.event === 'del') {
                        layer.confirm('确认删除？', function (index) {
                            $.post(url,params,function (result) {
                                if(result.code==0){
                                    layer.msg(result.msg, {icon: 1});
                                    configTable.reload({
                                        url: baseUrl+'get'
                                    });
                                } else {
                                    layer.msg(result.msg, {icon: 5});
                                }
                            })
                            layer.close(index);
                        })

                } else if (obj.event === 'edit') {
                    layer.open({
                        content: [baseUrl + 'config_update'],
                        type: 2,
                        title: '<h2>修改配置信息</h2>',
                        maxmin: true,
                        shadeClose: true, //点击遮罩关闭层
                        offset: '50px',
                        area: ['400px', '520px'],
                        success:function(layero,index){
                            var body = layer.getChildFrame('body',index);  //获取到子页面的内容
                            body.find('#name').val(data.name);
                            body.find('#value').val(data.value);
                            body.find('#desc').val(data.desc);
                            body.find('#id').val(data.id);
                            layer.iframeAuto(index);
                        },
                    });
                }
            });
        });
    </script>
</div>
</body>
</html>
